//
//  WSThreeColorGradientColorView.m
//  CharonTVProject
//
//  Created by karong on 2023/8/10.
//

#import "WSThreeColorGradientColorView.h"
@interface WSThreeColorGradientColorView ()

@property (nonatomic, assign) CGRect gradientLayerFrame;
@property (nonatomic, strong) CAGradientLayer *gradientLayer;

@end

@implementation WSThreeColorGradientColorView
- (void)layoutSubviews {
    [super layoutSubviews];
    _gradientLayer.frame = self.bounds;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    [self.gradientLayer removeFromSuperlayer];
    [self setupGradientLayer];
}

- (void)setLayerFrame:(CGRect)frame {
    self.gradientLayerFrame = frame;
    self.gradientLayer.frame = self.gradientLayerFrame;
}

- (void)setupGradientLayer {
    
    CAGradientLayer *layer = [[CAGradientLayer alloc] init];
    CGRect frame = self.bounds;
    if (CGRectEqualToRect(self.gradientLayerFrame, CGRectZero)) {
        layer.frame = frame;
    } else {
        layer.frame = self.gradientLayerFrame;
    }

    if (self.color1 && self.color2 && self.color3) {
        layer.colors = @[(__bridge id)self.color1.CGColor,
                         (__bridge id)self.color2.CGColor,
                         (__bridge id)self.color3.CGColor];
    } else {
        layer.colors = @[(__bridge id)[UIColor colorFromHexRGB:@"F9DFC5"].CGColor,
                         (__bridge id)[UIColor colorFromHexRGB:@"FCF3E6"].CGColor,
                         (__bridge id)[UIColor colorFromHexRGB:@"E3B792"].CGColor];
    }

    layer.locations = @[@0.0, @0.5, @1.0];
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(0, 1);
    [self.layer insertSublayer:layer atIndex:0];
    self.gradientLayer = layer;
}

- (void)resetCorlor1:(UIColor *)color1 color2:(UIColor *)color2 color3:(nonnull UIColor *)color3{
    _color1 = color1;
    _color2 = color2;
    _color3 = color3;

    [self.gradientLayer removeFromSuperlayer];
    self.gradientLayer = nil;
    [self setupGradientLayer];
}

- (void)resetCorlorByStyleDidChange {
    if (@available(iOS 12.0, *)) {
        if (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
            [self resetCorlor1:UIColor.bg_tint_black_1B1E32 color2:UIColor.bg_tint_black_1B1E32 color3:UIColor.bg_tint_black_1B1E32];
        }
        else {
            [self resetCorlor1:[UIColor colorFromHexRGB:@"F9DFC5"] color2:[UIColor colorFromHexRGB:@"FCF3E6"] color3:[UIColor colorFromHexRGB:@"E3B792"]];
        }
    } else {
        [self resetCorlor1:[UIColor colorFromHexRGB:@"F9DFC5"] color2:[UIColor colorFromHexRGB:@"FCF3E6"] color3:[UIColor colorFromHexRGB:@"E3B792"]];
    }
}
@end
